<template>
	<div class="app-container">
		<jk-operation-card ref="box1" class="margin-bottom-10">
			<div class="flex-between-center-wrap">
				<div class="flex-start-center-wrap">
					<!--					<jk-add-button :permission-prefix="prefix" class="margin-5-0 item-gap" @click="onAddBtn"></jk-add-button>-->
					<jk-report-button :permission-prefix="prefix" class="margin-5-0" :loading="exportLoading" @click="onReportBtn"></jk-report-button>

				</div><div class="flex-end-center-wrap">

					<div class="flex-end-center-wrap">
						<el-checkbox v-model="quickSearch">快捷筛选</el-checkbox>
						<el-radio-group v-if="quickSearch" v-model="searchParams.period" size="small" style="margin: 0 5px" @change="onStateChange">
							<el-radio-button label="1">本天</el-radio-button>
							<el-radio-button label="2">本周</el-radio-button>
							<el-radio-button label="3">本月</el-radio-button>
						</el-radio-group>
						<div v-else class="flex-center">
							<el-date-picker
								v-model="searchParams.yearMonth"
								:disabled="showBlongDate"
								:clearable="true"
								:picker-options="pickerOptions"
								size="small"
								style="width: 120px; margin: 0 0 0 5px"
								type="month"
								value-format="yyyy-MM"
								class=""
								placeholder="月"
								@change="onYearMonthChange"
							/>
							<jk-date-picker v-model="belongDate" :disabled="showYearMonth" :disabled-future-time="true" size="small" type="daterange" style="width: 280px; margin: 0 5px" value-format="yyyy-MM-dd" placeholder="选择日期" class="search-bar-item-size1 item-gap" @change="onBlongDateChange"></jk-date-picker>
						</div>
						<el-select v-model="searchParams.typeCode" placeholder="检验类型" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onWorkshopChange">
							<el-option
								v-for="item in examineList"
								:key="item.code"
								:label="item.name"
								:value="item.code"
							>
							</el-option>
						</el-select>
						<el-select v-model="searchParams.productNameOrCode" placeholder="品种名称" style="width: 160px;" :clearable="true" size="small" class="search-bar-item-size1 margin-5-0 item-gap" @change="onWorkshopChange">
							<el-option
								v-for="item in findDataList"
								:key="item.productCode"
								:label="item.productName"
								:value="item.productCode"
							>
							</el-option>
						</el-select>
						<jk-search-button @click="onSearchBtn"></jk-search-button>
					</div>

				</div>
			</div>
		</jk-operation-card>
		<jk-card>
			<jk-table
				ref="jkTable"
				:span-method="mergeRowMethod"
				:loading="tableLoading"
				:data="tableData"
				:height="tableHeight + 20"
			>
				<div
					v-for="(item, index) in tableHeader"
					:key="index"
				>
					<vxe-colgroup
						v-if="typeof item.key !== 'string'"
						:title="item.value"
						:field="typeof item.key !== 'string' ? 'aaa': item.key"
						:align="['belongDate','productName'].includes(item.key) ? 'center': 'center'"
						:width="item.width"
					>
						<vxe-column
							v-for="(childItem, childIndex) in item.key"
							:key="childIndex"
							:field="childItem.key"
							:title="childItem.value"
							align="right"
							:width="110"
						>
						</vxe-column>
					</vxe-colgroup>
					<vxe-column
						v-else
						:title="item.value"
						:fixed="item.fixed ? item.fixed : ''"
						:field="typeof item.key !== 'string' ? 'aaa': item.key"
						:align="['belongDate','batchCode', 'remark', 'qualitySituation'].includes(item.key) ? 'left' : 'center'"
						:min-width="['batchCode', 'remark', 'qualitySituation'].includes(item.key) ? '130': ['belongDate'].includes(item.key) ? '110' : '180'"
					>
						<template slot-scope="scope">
							<jk-common-status v-if="item.key === 'auditState'" :status="scope.row.auditState"></jk-common-status>
							<span v-else-if="item.key === 'productName'">
								<div style="display: flex; flex-direction: column; align-items: center;">
									{{ scope.row.productName }}
									<!--									<jk-button size="mini" icon="el-icon-plus" class="item-gap" @click="onAddBtn(scope.row, scope.rowIndex)"></jk-button>-->
								</div>
							</span>
							<span v-else>{{ scope.row[item.key] }}</span>
						</template>
					</vxe-column>
				</div>
			</jk-table>
		</jk-card>
	</div>
</template>

<script>
    import { auditStateList } from '@/utils/jk/status-option-list';
    // import saveDialog from './save-dialog';
    // import detailDialog from './detail-dialog';
    import calHeight from '/src/mixins/cal-table-height';
    import getMenuColumn from '../../../mixins/getMenuColumn';
    import handlerCache from '../../../mixins/handler-cache';
    import {
        spinQualityInspectionRecordDelete, spinQualityInspectionRecordExportExcel,
        spinQualityInspectionRecordPage
    } from '@/api/quality/qualityRecord';
    import { systemBusinessDictPage } from '../../../api/quality/processQuality';
    import { pageConfig, formatMonth, formatDate, tipsBar } from '/src/utils/jk/jk-tool';
    import { spinQualityInspectionRecordMonthData } from '../../../api/quality/qualityDayReportForms';
    export default {
        name: 'WorkshopArea',
        components: {
        },
        mixins: [calHeight, getMenuColumn, handlerCache],
        data() {
            return {
                prefix: 'spin:qualityInspectionRecord',
                apiItem: {
                    'page': spinQualityInspectionRecordMonthData,
                    'exportExcel': spinQualityInspectionRecordExportExcel,
                    'delete': spinQualityInspectionRecordDelete
                },
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                processList: [],
                examineList: [],
                belongDate: [],
                importDialogState: false,

                typeList: [],
                auditStateList: auditStateList,
                detailDialogState: false,
                quickSearch: false,
                productId: '',
                dataId: null,
                tableHeader: [],
                varietyData: {},
                batchData: {},
                saveDialogState: false,
                tableLoading: true,
                exportLoading: false,
                tableData: [],
                searchParams: {
                    yearMonth: '',
                    typeCode: '',
                    typeId: '',
                    productNameOrCode: '',
                    beginDate: '',
                    endDate: '',
                    radioTime: '',
                    period: 1
                },
                showYearMonth: true,
                showBlongDate: false,
                findDataList: []
            };
        },
        methods: {
            onYearMonthChange(e) {
                this.$set(this.searchParams, 'beginDate', '');
                this.$set(this.searchParams, 'endDate', '');
                if (e === null) {
                    this.showYearMonth = false;
                } else {
                    this.showYearMonth = true;
                }
            },
            onBlongDateChange(e) {
                if (e === null) {
                    this.belongDate = [];
                    this.$set(this.searchParams, 'beginDate', '');
                    this.$set(this.searchParams, 'endDate', '');
                    this.showBlongDate = false;
                } else {
                    this.$set(this.searchParams, 'beginDate', e[0]);
                    this.$set(this.searchParams, 'endDate', e[1]);
                    this.showBlongDate = true;
                }
            },
            mergeRowMethod({ row, _rowIndex, column, visibleData }) {
                const fields = ['productName'];
                const cellValue = row[column.field];
                if (cellValue && fields.includes(column.field)) {
                    const prevRow = visibleData[_rowIndex - 1];
                    let nextRow = visibleData[_rowIndex + 1];
                    if (prevRow && prevRow[column.field] === cellValue) {
                        return { rowspan: 0, colspan: 0 };
                    } else {
                        let countRowspan = 1;
                        while (nextRow && nextRow[column.field] === cellValue) {
                            nextRow = visibleData[++countRowspan + _rowIndex];
                        }
                        if (countRowspan > 1) {
                            return { rowspan: countRowspan, colspan: 1 };
                        }
                    }
                }
            },
            onStateChange() {
                this.getListRequest();
            },
            onWorkshopChange(e) {
                this.examineList.forEach(x => {
                    if (e === x.id) {
                        this.$set(this.searchParams, 'typeName', x.name);
                        this.$set(this.searchParams, 'typeCode', x.code);
                        this.$set(this.searchParams, 'typeId', x.id);
                    }
                });
                this.getListRequest();
            },
            getTypeListRequest() {
                const params = {
                    categoryCode: 'QUALITY_TYPE',
                    pageSize: 100,
                    pageNo: 1
                };
                return systemBusinessDictPage(params).then(res => {
                    if (res.data.status === 200) {
                        this.examineList = res.data.res || [];
                        if (!this.searchParams.typeCode) {
                            this.$set(this.searchParams, 'typeName', res.data.res[0].name);
                            this.$set(this.searchParams, 'typeCode', res.data.res[0].code);
                            this.$set(this.searchParams, 'typeId', res.data.res[0].id);
                        }
                    }
                });
            },
            /** 导出按钮操作 */
            onReportBtn() {
                const params = this.getDataParams();
                params.pageNo = null;
                params.pageSize = null;
                this.apiItem.page(params).then((res) => {
                    this.exportLoading = true;
                    if (res.data.status === 200) {
                        this.exportLoading = false;
                        const { tableData, tableHeader } = res.data.res;
                        const flatHeader = (header) => {
                            const result = [];

                            const traverse = (item) => {
                                if (Array.isArray(item.key)) {
                                    item.key.forEach(subItem => {
                                        result.push(subItem.key); // 直接提取数组中的 key
                                    });
                                } else {
                                    result.push(item.value); // 一级 value 直接提取
                                }
                            };

                            header.forEach(item => traverse(item));

                            return result;
                        };
                        // 提取 tableHeader 中的 key，并展平
                        const getFlattenedKeys = (headers) => {
                            const keys = [];
                            headers.forEach(header => {
                                if (Array.isArray(header.key)) {
                                    header.key.forEach(subHeader => {
                                        keys.push(subHeader.key);
                                    });
                                } else {
                                    keys.push(header.key);
                                }
                            });
                            return keys;
                        };
                        // 转换 tableData 为一维数组
                        const convertToArray = (tableHeader, tableData) => {
                            const flattenedKeys = getFlattenedKeys(tableHeader);
                            return tableData.map(row => {
                                return flattenedKeys.map(key => row[key] || ''); // 使用空字符串填充缺失的值
                            });
                        };
                        // 获取结果
                        import('@/vendor/Export2Excel').then(excel => {
                            const header = flatHeader(tableHeader);
                            const data = convertToArray(tableHeader, tableData);
                            data.forEach(item => {
                                if (item[0].substr(-2) === '竹节') {
                                    var index = item[0].indexOf('竹');
                                    var resolve = item[0].substring(0, index);
                                    item[0] = resolve;
                                }
                            });
                            excel.export_json_to_excel({
                                header,
                                data,
                                filename: `${this.$route.meta.title}(${formatDate(this.searchParams.yearMonth, '')})`,
                                autoWidth: true,
                                bookType: 'xlsx'
                            });
                        });
                    }
                });
            },
            getDataParams() {
                const params = JSON.parse(JSON.stringify(this.searchParams));

                if (params.yearMonth) {
                    const date = new Date(params.yearMonth);
                    params.year = date.getFullYear();
                    params.month = date.getMonth() + 1;
                }

                const now = new Date();
                params.period = Number(params.period);
                if (this.quickSearch) {
                    // 处理时间范围
                    const now = new Date();
                    params.period = Number(params.period);
                    if (this.quickSearch) {
                        const getDateRange = (period) => {
                            switch (period) {
                            case 1: // 本天
                                return [formatDate(now), formatDate(now)];
                            case 2: // 本周
                                // eslint-disable-next-line no-case-declarations
                                const startOfWeek = new Date(now);
                                startOfWeek.setDate(now.getDate() - now.getDay() + 1);
                                return [formatDate(startOfWeek), formatDate(new Date())];
                            case 3: // 本月
                                // eslint-disable-next-line no-case-declarations
                                const startOfMonth = new Date(now.getFullYear(), now.getMonth(), 1);
                                return [formatDate(startOfMonth), formatDate(new Date())];
                            default:
                                return [];
                            }
                        };
                        params.radioTime = getDateRange(params.period);
                        params.beginDate = params.radioTime[0];
                        params.endDate = params.radioTime[1];
                    }

                    // 根据 quickSearch 删除不同的属性
                    if (this.quickSearch) {
                        delete params.year;
                        delete params.month;
                    } else {
                        delete params.beginDate;
                        delete params.endDate;
                    }
                }
                delete params.typeName;
                delete params.typeId;
                delete params.period;
                delete params.radioTime;

                return params;
            },

            /** 查询列表 */
            getListRequest() {
                this.tableLoading = true;
                this.tableHeader = [];
                this.tableData = [];
                this.apiItem.page(this.getDataParams()).then(res => {
                    this.tableLoading = false;
                    if (res.data.status === 200) {
                        this.tableData = res.data.res ? res.data.res.tableData : [];
                        this.getTableDataList();
                        const arr = [];
                        res.data.res ? res.data.res.tableHeader.forEach(x => {
                            arr.push({
                                value: x.value,
                                key: x.key,
                                fixed: ['productName'].includes(x.key) ? 'left' : '',
                                width: ['productName'].includes(x.key) ? 180 : 110,
                                align: ['productName'].includes(x.key) ? 'left' : 'right'
                            });
                            return x;
                        }) : [];
                        this.tableHeader = arr || [];
                        this.$nextTick(() => {
                            // this.$refs.jkTable.$refs.xTable.refreshColumn();
                        });
                    }
                });
            },
            getTableDataList() {
                const uniqueObjects = this.tableData.filter((item, index, self) => {
                    return self.findIndex(t => t.productName === item.productName) === index;
                });
                this.findDataList = uniqueObjects;
            },
            /** 搜索按钮操作 */
            onSearchBtn() {
                this.searchParams.pageNo = 1;
                this.searchParams.count = 1;
                this.getListRequest();
            },
            /** 新增按钮操作 */
            onAddBtn(item, index) {
                if (item && index || index === 0) {
                    this.varietyData = {
                        productName: item.productName,
                        productId: item.productId,
                        batchCode: item.batchCode
                    };
                } else {
                    this.varietyData = {};
                }
                this.saveDialogState = true;
            },
            async getDependentData() {
                if (!this.searchParams.yearMonth) {
                    this.$set(this.searchParams, 'yearMonth', formatMonth(Date.now()));
                }
                await this.getTypeListRequest();
                this.processList = this.$store.state.user.userProcess.processList;
                await this.getMenuColumnListRequest();
                await this.getListRequest();
            }
        },
        mounted() {
            this.getDependentData();
        }
    };
</script>
